package com.zhugang.week07;

/**
 * @program algorithms
 * @description: trie
 * @author: chanzhugang
 * @create: 2022/08/02 14:23
 */
public class Trie {

    /**
     * 208 实现Trie（前缀树）
     * 情景：自动补完和拼写检查
     */

    private TrieNode root;

    public Trie() {
        root = new TrieNode('/');
    }

    public void insert(String word) {
        TrieNode p = root;
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            if (p.children[c - 'a'] == null) {
                p.children[c - 'a'] = new TrieNode(c);
            }
            p = p.children[c - 'a'];
        }
        p.isEnding = true;
    }

    public boolean search(String word) {
        TrieNode p = root;
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            if (p.children[c - 'a'] == null) {
                return false;
            }
            p = p.children[c - 'a'];
        }
        return p.isEnding;
    }

    public boolean startWith(String prefix) {
        TrieNode p = root;
        for (int i = 0; i < prefix.length(); i++) {
            char c = prefix.charAt(i);
            if (p.children[c - 'a'] == null) {
                return false;
            }
            p = p.children[c - 'a'];
        }
        return true;
    }


    private class TrieNode {
        char data;
        boolean isEnding = false;
        TrieNode[] children = new TrieNode[26];

        public TrieNode(char data) {
            this.data = data;
        }
    }
}